<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { ContentWrap } from '@/components/ContentWrap'
import { useI18n } from '@/hooks/web/useI18n'
import { dashboardApi } from '@/api/dashboard'
import { formatDate } from '@/utils/formatTime'

const { t } = useI18n()

// 表格数据
const tableData = ref([])
const loading = ref(false)
const total = ref(0)
const sortType = ref('1')  // 排序类型
const isNew = ref(false)  // 只看新短剧
const clipVal = ref('')  // 剪切板内容

// 分页参数
const pageParams = ref({
  pageNo: 1,
  pageSize: 20
})

// 搜索表单
const searchForm = ref({
  category: '',
  genre: '',
  platform: '',
  status: '',
  publishTime: [],
})

// 类型选项
const categoryOptions = ref([])

const statusOptions = [
  { label: '全部', value: '' },
  { label: '正常', value: '正常' }
]

// 获取数据
const fetchData = async () => {
  loading.value = true
  dashboardApi
    .getDataAnalysis({
      category: searchForm.value.category ? searchForm.value.category : '',
      pageSize: pageParams.value.pageSize,
      pageNo: pageParams.value.pageNo,
      name: searchForm.value.genre ? searchForm.value.genre : clipVal.value ? clipVal.value : '',
      sort: sortType.value,
      queryStatus: isNew.value ? 1 : 0
    })
    .then((res) => {
      tableData.value = res.list.map(v => {
        v.topics = v.topics ? JSON.parse(v.topics) : []
        return v
      })
      total.value = res.total
    })
    .finally(() => {
      loading.value = false
    })
}

// 搜索
const handleSearch = () => {
  pageParams.value.pageNo = 1
  fetchData()
}

// 重置搜索
const handleReset = async () => {
  searchForm.value = {
    category: '',
    genre: '',
    platform: '',
    status: '',
    publishTime: []
  }
  pageParams.value.pageNo = 1
  isNew.value = false
  sortType.value = '1'
  clipVal.value = ''
  fetchData()
}

// 分页变化
const handlePageChange = (page) => {
  pageParams.value.pageNo = page
  fetchData()
}

const handleSizeChange = (size) => {
  pageParams.value.pageSize = size
  pageParams.value.pageNo = 1
  fetchData()
}

// 格式化数字
const formatNumber = (num) => {
  if (num === null || num === undefined) return '-'
  return num.toLocaleString()
}

// 获取状态类型
const getStatusType = (status) => {
  switch (status) {
    case '正常':
      return 'success'
    case '异常':
      return 'danger'
    case '待审核':
      return 'warning'
    default:
      return 'info'
  }
}

// 导出数据
const handleExport = () => {
  ElMessage.success('导出功能开发中...')
}

function handleClickType(item) {
  if (searchForm.value.category === item.label) {
    searchForm.value.category = ''
  } else {
    searchForm.value.category = item.label
  }
  handleSearch()
}

function getClip(text) {
  // 将文本内容写入剪切板
  navigator.clipboard.writeText(text).then(() => {
    ElMessage.success('已复制到剪切板，可直接粘贴')
  })
}

function getClipTopic(topics) {
  let text = ''
  topics.forEach((item) => {
    text += "#"+item + ' '
  })
  getClip(text)
}

function handleCompare() {
  searchForm.value.genre = ''
  navigator.clipboard.readText().then(res => {
    clipVal.value = res
    handleSearch()
    // res = res.replaceAll('端：', '').replaceAll('融合：', '').replaceAll('\r', '').replaceAll('"', '')
    // console.log(res)
    // // 根据/n分割
    // const names = res.split('\n')
    // console.log(names)
  })
}

// 生命周期
onMounted(() => {
  dashboardApi.getCategoryList().then((res) => {
    categoryOptions.value = res.map((item) => ({
      label: item.name,
      value: item.id
    }))
    console.log('res', categoryOptions.value)
  })
  fetchData()
})
</script>

<template>
  <ContentWrap>
    <!-- 搜索表单 -->
    <div class="mb-4">
      <el-form-item label="类型">
        <el-space wrap>
          <div
            class="type-item"
            :class="{ checked: searchForm.category === item.label}"
            v-for="item,index in categoryOptions"
            :key="index"
            @click="handleClickType(item)"
          >{{ item.label }}</div>
        </el-space>
      </el-form-item>
      <el-form :model="searchForm" inline>
        <el-form-item>
          <el-checkbox v-model="isNew">只看新短剧</el-checkbox>
        </el-form-item>

        <el-form-item label="剧名搜索">
          <el-input v-model="searchForm.genre" placeholder="搜索" style="width: 200px" clearable @change="clipVal=''" />
        </el-form-item>

        <el-form-item>
          <el-button @click="handleReset">重置搜索</el-button>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <!-- <el-button type="success" @click="handleExport">导出</el-button> -->
        </el-form-item>
      </el-form>
      <el-space>
          <el-select v-model="sortType" style="width: 200px" placeholder="排序方式" @change="handleSearch">
            <el-option label="按播放量增量排序" value="1" />
            <el-option label="按发布时间排序" value="0" />
          </el-select>
          <el-button type="primary" @click="handleCompare">对比剪切板剧名</el-button>
      </el-space>
    </div>

    <!-- 数据表格 -->
    <el-table v-loading="loading" :data="tableData" border stripe style="width: 100%">
      <el-table-column prop="id" label="序号" width="60" align="center" >
        <template #default="{$index}">
          {{ ($index+1)+(pageParams.pageNo-1)*pageParams.pageSize }}
        </template>
      </el-table-column>
      <el-table-column prop="publishTime" label="发布日期" min-width="180" align="center">
        <template #default="{ row }">
          {{ formatDate(row.publishTime) }}
        </template>
      </el-table-column>
      <el-table-column prop="name" label="剧名" min-width="120" show-overflow-tooltip>
        <template #default="{ row }">
          {{ row.name || '-' }}
        </template>
      </el-table-column>
      <el-table-column prop="category" label="类型" width="100" align="center">
        <template #default="{ row }">
          {{ row.category || '-' }}
        </template>
      </el-table-column>
      <el-table-column prop="totalEpisodes" label="集数" width="60" align="center">
        <template #default="{ row }">
          {{ row.totalEpisodes || '-' }}
        </template>
      </el-table-column>
      <!-- <el-table-column prop="likeCount" label="点赞数" width="100" align="center" /> -->
      <el-table-column prop="playCount" label="播放量" width="100" align="center" />
      <!-- <el-table-column prop="collectCount" label="收藏数" width="100" align="center" />
      <el-table-column prop="commentCount" label="评论数" width="100" align="center" /> -->
      <el-table-column prop="tags" label="标签" width="100" align="center">
        <template #default="{ row }">
          <el-tag @click="getClip('#'+row.tags)">{{ row.tags }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="topics" label="话题" align="center">
        <template #default="{ row }">
          <el-tag v-for="item in row.topics" :key="item" @click="getClipTopic(row.topics)">{{ item }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="authors" label="账号信息" width="100" align="center">
        <template #default="{ row }">
          {{ row.authors?.nickname || '-' }}
        </template>
      </el-table-column>
      <el-table-column prop="authors" label="抖音ID" min-width="180" align="center">
        <template #default="{ row }">
          <el-tag type="success">{{ row.authors?.douyinId || '-' }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="authors" label="总关注" width="100" align="center">
        <template #default="{ row }">
          <el-tag type="success">{{ row.authors?.followers || '-' }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="authors" label="点赞人数" width="100" align="center">
        <template #default="{ row }">
          <el-tag type="success">{{ row.authors?.totalWorks || '-' }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="authors" label="总点赞量" width="100" align="center">
        <template #default="{ row }">
          <el-tag type="success">{{ row.authors?.totalLikes || '-' }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="updatedAt" label="拉取时间" width="240" align="center" >
        <template #default="scope">
          {{ formatDate(scope.row.updatedAt) }}
        </template>
      </el-table-column>
      <!-- <el-table-column prop="detail_url" label="播放地址" align="center">
        <template #default="{ row }">
          {{ row.detail_url || '-' }}
        </template>
      </el-table-column> -->
    </el-table>

    <!-- 分页 -->
    <div class="mt-4 flex justify-end">
      <el-pagination
        v-model:current-page="pageParams.pageNo"
        v-model:page-size="pageParams.pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handlePageChange"
      />
    </div>
  </ContentWrap>
</template>

<style scoped lang="scss">
.type-item {
  cursor: pointer;
}

.checked {
  color: #409eff;
}
</style>
